package org.holynite.fieldmanage.entities

import org.holynite.fieldmanage.Utils.SecurityEngine
import org.holynite.fieldmanage.Utils.SecurityException
import sun.misc.BASE64Decoder

import javax.persistence.*

/**
 * Created by midnite on 15/1/2.
 */
@Entity
@Table(name = "supervisor")
class Administrator implements Serializable {
	@Transient
	private final String sk = "dmhKdmZlSEwyTSs4eSlva2c3d1FaezJCVFFDY0Y4ZHk="

	@Id
	@Column(name = "work_id", nullable = false, length = 30, unique = true)
	String workdId
	@Column(name = "name", nullable = false, length = 50)
	String name
	@Column(name = "pass", nullable = false, length = 200)
	String password
	@Column(name = "disabled", nullable = false)
	Boolean disabled = false
	@Column(name = "create", nullable = false)
	@Temporal(TemporalType.DATE)
	Date create
	@Column(name = "last_login", nullable = false)
	@Temporal(TemporalType.TIMESTAMP)
	Date lastLogin
	@Column(name = "admin_role")
	String correspondRole
	@Transient
	AdministratorRole role

	boolean equals(o) {
		if (this.is(o)) return true
		if (getClass() != o.class) return false

		Administrator that = (Administrator) o

		if (workdId != that.workdId) return false

		return true
	}

	int hashCode() {
		return (workdId != null ? workdId.hashCode() : 0)
	}

	@PrePersist
	void encryptPassword() {
		try {
			def k = new String(new BASE64Decoder().decodeBuffer(sk))
			def engine = new SecurityEngine(k);
			password = engine.encrypt(password)
		} catch (SecurityException e) {
			println "${e.exceptionMessage}"
		}
	}

	@PostLoad
	void decryptPassword() {
		try {
			def k = new String(new BASE64Decoder().decodeBuffer(sk))
			def engine = new SecurityEngine(k);
			password = engine.decrypt(password)
		} catch (SecurityException e) {
			println "${e.exceptionMessage}"
		}
	}

	@PreUpdate
	void encryptUpdatePassword() {
		try {
			def k = new String(new BASE64Decoder().decodeBuffer(sk))
			def engine = new SecurityEngine(k);
			password = engine.encrypt(password)
		} catch (SecurityException e) {
			println "${e.exceptionMessage}"
		}
	}

	@PostUpdate
	void decryptUpdatePassword() {
		try {
			def k = new String(new BASE64Decoder().decodeBuffer(sk))
			def engine = new SecurityEngine(k);
			password = engine.decrypt(password)
		} catch (SecurityException e) {
			println "${e.exceptionMessage}"
		}
	}
}
